package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import connection.JDCConnection;

import model.Cours;

public class CoursDAO {

	public Cours getCours(JDCConnection connection, int idCours) {
		Cours cours = new Cours();
		Statement stmt;
		ResultSet rs;

		try {

			stmt = connection.createStatement();

			rs = stmt.executeQuery("SELECT * FROM Cours where idCours="
					+ idCours);
			while (rs.next()) {

				cours.setIdCours(rs.getInt("idCours"));
				cours.setSigle(rs.getString("sigle"));
				cours.setDisponible(rs.getBoolean("disponible"));
				cours.setPreRequis(rs.getInt("preRequis"));
				cours.setNbCredit(rs.getInt("nbCredit"));
				cours.setDescription(rs.getString("description"));

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cours;
	}
	public ArrayList<Cours> getCoursPossibleByEtudiant(JDCConnection connection, int idEtudiant) {
		ArrayList<Cours> list = new ArrayList<Cours>();
		Statement stmt;
		ResultSet rs;

		try {
					
			stmt = connection.createStatement();

			rs = stmt.executeQuery("SELECT Distinct Cours.idCours,sigle,disponible,preRequis,nbCredit,description FROM Cours,Historique" +
					" where Cours.idCours NOT IN (SELECT idcours From Historique where Historique.idEtudiant="+idEtudiant+")");
						
							
			while (rs.next()) {
				Cours cours= new Cours();
				
				cours.setIdCours(rs.getInt("idCours"));
				cours.setSigle(rs.getString("sigle"));
				cours.setDisponible(rs.getBoolean("disponible"));
				cours.setPreRequis(rs.getInt("preRequis"));
				cours.setNbCredit(rs.getInt("nbCredit"));
				cours.setDescription(rs.getString("description"));
				
				if(verifierPreRequis(connection, cours, idEtudiant)){
					list.add(cours);
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	//retour true si etudient peut  prendre ce cours
	private boolean verifierPreRequis(JDCConnection connection,Cours cours,int idEtudiant){
	
		boolean autoriser=false;
		Statement stmt;
		ResultSet rs;
		
		try {
			
			stmt = connection.createStatement();
			rs = stmt.executeQuery("SELECT * FROM Cours where idCours="+cours.getIdCours()+" and preRequis not in (Select Distinct idCours from Historique where idEtudiant="+idEtudiant+")");
			boolean test =rs.first();
		
		if(rs.first()==false || rs.getInt("preRequis")==0){
				autoriser =true;	
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return autoriser;
	}

}
